package com.shj.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.shj.entity.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 *@Description spring security配置
 *@Author songhuajian //@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled =true, jsr250Enabled = true)
 *@Date 2020/1/10 23:18
 **/
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 自定义暂无权限处理器处理器
     */
    @Autowired
    private UserAuthAccessDeniedHandler userAuthAccessDeniedHandler;
    @Autowired
    private CustomAuthenticationFailureHandler customAuthenticationFailureHandler;
    @Autowired
    private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
    @Autowired
    private MyAccessDecisionManager myAccessDecisionManager;
    @Autowired
    private MyFilterInvocationSecurityMetadataSource myFilterInvocationSecurityMetadataSource;
    @Autowired
    private LoginValidateProvider loginValidateProvider;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .formLogin()
                .loginPage("/jsp/login.jsp")
                .loginProcessingUrl("/login")
                //.defaultSuccessUrl("/index.jsp")
                .permitAll()
                //登录失败处理器
                .failureHandler(customAuthenticationFailureHandler)
                //登录成功处理器
                .successHandler(customAuthenticationSuccessHandler)
                .and()
            .authorizeRequests()
                //hasRole默认加了ROLE_,所以只用写之后的
//                .antMatchers("/**").hasRole("USER")
//                .anyRequest().authenticated()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                        object.setAccessDecisionManager(myAccessDecisionManager);
                        object.setSecurityMetadataSource(myFilterInvocationSecurityMetadataSource);
                        return object;
                    }
                })
                .and()

                .exceptionHandling()
                .accessDeniedHandler(userAuthAccessDeniedHandler)
                .and()
            .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/jsp/login.jsp")
                .invalidateHttpSession(true);

        //关闭csrf跨域攻击防御
        http.csrf().disable();

        //解决iframe拒绝问题
        http.headers().frameOptions().disable();
    }

    /**
     * @description 设置资源不拦截
     * @author songhuajian
     * @date 2020/1/11 19:59
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/swagger-ui.html", "/css/**", "/js/**",
                "/images/**", "/jsp/login.jsp", "/jsp/**.jsp", "/WEB-INF/page/**/**.jsp", "/third/**");
    }

    /**
     * @description 设置自定义验证登录
     * @author songhuajian
     * @date 2020/1/11 0:11
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(loginValidateProvider);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * BCrypt加密
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}
